<template>
  <j-modal
    :title="title"
    :width="width"
    :style="modalStyle"
    :class="'jeecg-online-modal'"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    switch-fullscreen
    :destroyOnClose="true">
    <a-spin :spinning="confirmLoading">
      <component
        v-if="this.formComponent"
        ref="customFormRef"
        :url="onlineFormEditUrl"
        :is="customForm"
        :row="row"
        @close="handleSuccess">
      </component>
      <online-form
        v-else
        ref="onlineForm"
        @onSuccess="handleSuccess"
        :formSchema="schema"
        :uiSchema="uiSchema"
        :single="single"
        :tree="treeForm">
      </online-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { getAction } from '@/api/manage'
  import OnlineFormSwitch from '@/components/online/autoform/OnlineFormSwitch';
  const defaultModalConfig = {
    title: '自定义弹框',
    width: 600,
    row: {},
    hide: [],
    show: [],
    requestUrl: '',
    tableType: '',
    foreignKeys: []
  }
  export default {
    name: 'OnlErpCustomModal',
    components:{
      OnlineFormSwitch
    },
    data(){
      return {
        title: '',
        width: '',
        modalStyle: { 'position': 'relative' },
        visible: false,
        confirmLoading: false,
        formComponent: '',
        row: {},
        code: '',
        url:{
          loadFormItems:"/online/cgform/api/getErpFormItem/",
          optPre:"/online/cgform/api/form/"
        },
        uiSchema:{
          itemattrs: ""
        },
        formTemplate: 1,
        single: true,
        treeForm: false,
        schema: {},
        hide: [],
        show: [],
        requestUrl: '',
        tableType: '',
        foreignKeys: []
      }
    },
    computed: {
      customForm(){
        // 弹窗内表单每次都会走created事件
        if(this.formComponent){
          return () => import(`@/views/${this.formComponent}`)
        }else{
          return OnlineFormSwitch
        }
      },
      onlineFormEditUrl(){
        if(this.requestUrl){
          return this.requestUrl
        }else{
          return this.url.optPre+this.code
        }
      },
      modalWidth() {
        let formTemplate = 1;
        if (this.uiSchema.formTemplate) {
          try {
            formTemplate = Number.parseInt(this.uiSchema.formTemplate)
          } catch {
            console.warn('error formTemplate value: ', this.uiSchema.formTemplate)
          }
        }
        // 不同的列数展示不同的宽度
        let diff = 200 * (formTemplate - 1)
        // 基值加上阈值
        let width = (this.single ? singleWidth : one2ManyWidth) + diff
        console.log('-- modalWidth: ',width)
        return width
      }
    },
    methods:{
      open(param){
        // title width code row formComponent formTemplate hide show
        let obj = Object.assign({}, defaultModalConfig, param)
        Object.keys(obj).map(k=>{
          if(obj[k]){
            this[k] = obj[k]
          }
        })

        this.visible = true
        if(!this.formComponent){
          this.handleUiSchema();
          this.loadOnlineFormConfig()
        }

      },
      handleOk(){
        this.submitLoading = true
        if(!this.formComponent){
          this.$refs.onlineForm.handleSubmit();
        }else{
          this.$refs.customFormRef.handleSubmit();
        }
        setTimeout(()=>{
          this.submitLoading = false
        },3500)
      },
      handleCancel(){
        this.visible = false
      },
      handleUiSchema(){
        this.uiSchema.method = "put"
        this.uiSchema.formTemplate = this.formTemplate
        this.uiSchema.url = this.onlineFormEditUrl
        this.uiSchema = { ...this.uiSchema }
      },
      // 处理子表的 外键问题
      initForeignKeyForm(){
        if(this.foreignKeys && this.foreignKeys.length>0){
          for(let item of this.foreignKeys){
            this.schema.properties[item.field]={
              hidden: true,
              key: item.field,
              title: item.field,
              type: 'string',
              view: 'hidden'
            }
          }
        }
        console.log("this.schema",this.schema)
      },
      /**加载online表单*/
      loadOnlineFormConfig(){
        if(!this.code){
          this.$message.warning('表单不识别')
          return;
        }
        this.confirmLoading = true
        getAction(`${this.url.loadFormItems}${this.code}`).then(res=>{
          if(res.success){
            this.single = true
            this.schema = res.result.schema
            this.initForeignKeyForm();
            this.treeForm = res.result.head.isTree=='Y'
            this.$nextTick(() => {
              if(this.$refs.onlineForm){
                this.$refs.onlineForm.createRootProperties()
                this.$refs.onlineForm.handleCustomFormSh(this.show, this.hide);
                this.loadOnlineFormData();
              }
            });
          }
        }).catch(()=>{
          this.confirmLoading = false
        })
      },
      /**加载online表单数据*/
      loadOnlineFormData(){
        getAction(this.url.optPre+this.code+"/"+this.row.id).then((res)=>{
          if(res.success){
            let record = res.result
            this.$refs.onlineForm.edit(record)
          }else{
            this.$message.warning(res.message)
          }
        }).finally(()=>{
          this.confirmLoading = false
        })
      },
      handleSuccess(){
        this.visible = false
        this.$emit('success');
      }

    }
  }
</script>
